package com.example.fileuploadpart;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;

@WebServlet("/upload")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024,  // 内存缓冲阈值（1MB）
        maxFileSize = 1024 * 1024 * 5,    // 单个文件最大5MB
        maxRequestSize = 1024 * 1024 * 10 // 请求总大小最大10MB
)
public class FileUploadServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        try {
            // 1. 获取上传文件
            Part filePart = request.getPart("file");
            String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();

            // 2. 校验文件类型（例如仅允许图片）
            if (!fileName.toLowerCase().endsWith(".jpg") && !fileName.toLowerCase().endsWith(".png")) {
                throw new ServletException("仅支持 JPG/PNG 文件");
            }

            // 3. 指定安全保存路径（避免路径遍历漏洞）
            String uploadPath = getServletContext().getRealPath("/uploads");
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) uploadDir.mkdirs();

            // 4. 保存文件
            String safeFileName = UUID.randomUUID() + "_" + fileName; // 防止文件名冲突
            String filePath = uploadPath + File.separator + safeFileName;
            filePart.write(filePath);

            // 5. 返回成功响应
            response.getWriter().print("文件上传成功: " + safeFileName);
        } catch (Exception e) {
            response.getWriter().print("上传失败: " + e.getMessage());
        }
    }
}